
package com.android.JiYclocks;

import java.util.Calendar;

import com.android.JiYclock.Alarm;
import com.android.JiYclock.AlarmClock;
import com.android.JiYclock.Log;
import com.android.JiYclock.Alarm.Columns;
import com.android.JiYclock.R;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Parcel;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.format.DateFormat;

/**
 * 
 * The Alarms provider提供的关于闹钟设置的的信息
 * 这个类主要是记录了关于闹钟的一些业务逻辑
 */
public class SpecialAlarms {
	
	public static final int ALARM_STATUSBAR_CANCEL = 0;
	public static final int ALARM_STATUSBAR_NOTIFY = 1;
	public static final int ALARM_STATUSBAR_INVARIANT = 2;
	
	
    
    public static final String SPECIALALARM_ALERT_ACTION = "com.android.superdeskclocks.ALARM_ALERT";


    //由AlarmKalxon发送，当闹钟被中止闹铃
    //中止的原因有很多，比如说在AlarmAlertFullScreen中被取消
    //当然，被电话中止也有可能
    public static final String SPECIALALARM_DONE_ACTION = "com.android.superdeskclocks.ALARM_DONE";

    //AlarmAlertFullScreen 监听这个广播Intent，这样的话其他的应用程序能够小睡闹钟
    //  (after ALARM_ALERT_ACTION and before ALARM_DONE_ACTION).
    public static final String SPECIALALARM_SNOOZE_ACTION = "com.android.superdeskclocks.ALARM_SNOOZE";

    // AlarmAlertFullScreen 监听这个广播Intent，这样的话其他的应用程序能够取消闹钟
    // (after ALARM_ALERT_ACTION and before ALARM_DONE_ACTION).
    public static final String SPECIALALARM_DISMISS_ACTION = "com.android.superdeskclocks.ALARM_DISMISS";

    //这个Action是AlarmKlaxon用来更新UI，当这个闹钟被杀掉以后
    public static final String SPECIALALARM_KILLED = "special_alarm_killed";

   
    //Alarm_Killed intent的额外信息，用来说明这个闹钟再被杀掉之前已经执行了多久
    public static final String SPECIALALARM_KILLED_TIMEOUT = "specialalarm_killed_timeout";

    // 这个字符串用来表明这个闹钟在数据库中是静音的
    public static final String SPECIALALARM_ALERT_SILENT = "special_silent";

    // This intent is sent from the notification when the user cancels the
    // snooze alert.
    
    public static final String SPECIALCANCEL_SNOOZE = "special.cancel_snooze";

    // This string is used when passing an Alarm object through an intent.
    public static final String SPECIALALARM_INTENT_EXTRA = "special.intent.extra.alarm";

    // This extra is the raw Alarm object data. It is used in the
    // AlarmManagerService to avoid a ClassNotFoundException when filling in
    // the Intent extras.
    public static final String SPECIALALARM_RAW_DATA = "special.intent.extra.alarm_raw";

    // This string is used to identify the alarm id passed to SetAlarm from the
    // list of alarms.
    public static final String ALARM_ID = "alarm_id";

    final static String PREF_SNOOZE_ID = "snooze_id";
    final static String PREF_SNOOZE_TIME = "snooze_time";

    private final static String DM12 = "E h:mm aa";
    private final static String DM24 = "E k:mm";

    private final static String M12 = "h:mm aa";
    final static String M24 = "kk:mm";

    /**
     * 创建一个新的闹钟，然后用一个指定的ID
     */
    public static long addAlarm(Context context, SpecialAlarm alarm) {
    	
    	int c1=count(context);
        ContentValues values = createContentValues(alarm);
        Uri uri = context.getContentResolver().insert(SpecialAlarm.Columns.CONTENT_URI, values);
        alarm.id = (int) ContentUris.parseId(uri);

        int c2=count(context);
        //获得距离闹钟闹铃还剩下多少时间
        //新建一个闹钟的话，不考虑这个小睡的操作，因此，暂时将这段代码注释掉
       long timeInMillis = calculateAlarm(alarm);
//        if (alarm.enabled) {
//            clearSnoozeIfNeeded(context, timeInMillis);
//        }
   
        
        updateStatusBarIcon(c1,c2,context);
        setNextAlert(context);
        return timeInMillis;
    }

    /**
     * Removes an existing Alarm.  If this alarm is snoozing, disables
     * snooze.  Sets next alert.
     */
    public static void deleteAlarm(Context context, int alarmId) {

    	Log.v("DeleteAlarm--------是否执行删除闹钟");
        ContentResolver contentResolver = context.getContentResolver();
        /* If alarm is snoozing, lose it */
        disableSnoozeAlert(context, alarmId);
        
        //先将当前的这个闹钟给取消，然后再获取下一个闹钟
        CancelAlarmService(context);
        
        Uri uri = ContentUris.withAppendedId(SpecialAlarm.Columns.CONTENT_URI, alarmId);
        contentResolver.delete(uri, "", null);
        int c1=count(context);
        setNextAlert(context);
        int c2=count(context);
        updateStatusBarIcon(c1,c2,context);
    }
   
    /**
     * 
     * @param Context context
     * @return
     */
    
    public static void CancelAlarmService(Context context)
    {
    	 Intent intent = new Intent(SpecialAlarms.SPECIALALARM_ALERT_ACTION);   
         PendingIntent pi= PendingIntent.getBroadcast(
                 context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
         AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
         am.cancel(pi);
    }
    
    
    /**
     *  
     * @param Specialalarm
     * @return String location
     * 通过存储在MediaStore记录的Uri来获取到这个音频文件的存储位置
     */
     
     public static String  getLocationOfRecord(Context context,SpecialAlarm alarm)
     {
     	String location = null;
     	String temp[]= new String[]{MediaStore.Audio.Media.DATA};
     	 Uri uri = Uri.parse(alarm.location);
     	 ContentResolver resolver = context.getContentResolver();
     	 Cursor cursor = resolver.query(uri, temp, null, null, null);
     	 if(cursor != null)
     	 {
     		 if(cursor.moveToFirst())
     		 {
     			 location = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
     		 }
     	 }
     	 return location;
     }
    
     /**
      *  
      * @param alarm
      * @return Long 
      */
        public static Long getMillTime(SpecialAlarm specialalarm)
        {
        	Calendar calendar = Calendar.getInstance();
        	calendar.setTimeInMillis(System.currentTimeMillis());
        	calendar.set(Calendar.YEAR, specialalarm.year);
        	calendar.set(Calendar.MONTH, specialalarm.month);
        	calendar.set(Calendar.DAY_OF_MONTH, specialalarm.day);
        	calendar.set(Calendar.HOUR, specialalarm.hour);
        	calendar.set(Calendar.MINUTE, specialalarm.minutes);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Long temp = calendar.getTimeInMillis();
            return temp;
        }
        
       /**
        * 调用系统短信发送界面，将信息发送出去
        * @param context
        * @return
        */

        public static void SendColorMessage(Context context ,Long longtime,String Urilocation)
        {
        	Intent intent = new Intent(Intent.ACTION_SEND);
    	    intent.putExtra("subject", "JiYclock"); 
    	    intent.putExtra("sms_body", String.valueOf(longtime));
    	    intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(Urilocation));
    	    intent.setType("audio/"+"3gp");
    	    context.startActivity(intent);
        }
        
        
        
    //统计闹钟的数量
    public static int count(Context context){
    	Cursor cur = getFilteredAlarmsCursor(context.getContentResolver());
        int conut=0;
        if (cur.moveToFirst()) {
            do {
                SpecialAlarm alarm = new SpecialAlarm(cur);
                if(alarm.enabled){
                	conut++;
                }
            } while (cur.moveToNext());
        }
        cur.close();
        return conut;
    }
    
    public static void updateStatusBarIcon(int c1,int c2,Context context){
    	if(c1<c2)
    		setStatusBarIcon(context, true);
    	else if(c1>c2&&c2==0)
    		setStatusBarIcon(context, false);
    }

    /**
     * Queries all alarms
     * @return cursor over all alarms
     */
    public static Cursor getAlarmsCursor(ContentResolver contentResolver) {
        return contentResolver.query(
                SpecialAlarm.Columns.CONTENT_URI, SpecialAlarm.Columns.ALARM_QUERY_COLUMNS,
                null, null, SpecialAlarm.Columns.DEFAULT_SORT_ORDER);
    }

    //返回的所有闹钟都是已经激活的闹钟
    private static Cursor getFilteredAlarmsCursor(ContentResolver contentResolver) {
    	
        return 
        contentResolver.query(SpecialAlarm.Columns.CONTENT_URI,
                SpecialAlarm.Columns.ALARM_QUERY_COLUMNS, SpecialAlarm.Columns.WHERE_ENABLED,
                null, null);
    }

//    通过一个Alarm对象，创建一个ContentValues对象
    
    public static ContentValues createContentValues(SpecialAlarm alarm) {
//        ContentValues values = new ContentValues(8);
        ContentValues values = new ContentValues(14);
        
        // Set the alarm_time value if this alarm does not repeat. This will be
        // used later to disable expire alarms.
        long time = 0;
            time = calculateAlarm(alarm);
        

        values.put(SpecialAlarm.Columns.ENABLED, alarm.enabled ? 1 : 0);
        values.put(SpecialAlarm.Columns.YEAR, alarm.year);
        values.put(SpecialAlarm.Columns.MONTH, alarm.month);
        values.put(SpecialAlarm.Columns.DAY, alarm.day);
        values.put(SpecialAlarm.Columns.HOUR, alarm.hour);
        values.put(SpecialAlarm.Columns.MINUTES, alarm.minutes);
        values.put(SpecialAlarm.Columns.ALARM_TIME, alarm.time);
        values.put(SpecialAlarm.Columns.VIBRATE, alarm.vibrate);
        values.put(SpecialAlarm.Columns.MESSAGE, alarm.label);
        values.put(SpecialAlarm.Columns.ALERT, alarm.alert == null ? SPECIALALARM_ALERT_SILENT : alarm.alert.toString());
        values.put(SpecialAlarm.Columns.TIMES, alarm.times);
        values.put(SpecialAlarm.Columns.INTERVAL, alarm.interval);
        values.put(SpecialAlarm.Columns.LOCATION,alarm.location);
        
        return values;
    }

    
    //
    
    private static void clearSnoozeIfNeeded(Context context, long alarmTime) {
        // If this alarm fires before the next snooze, clear the snooze to
        // enable this alarm.
        SharedPreferences prefs =
                context.getSharedPreferences(AlarmClock.PREFERENCES, 0);
        long snoozeTime = prefs.getLong(PREF_SNOOZE_TIME, 0);
        //如果闹钟的响应时间小于小睡时间，直接就清除掉这个小睡
        if (alarmTime < snoozeTime) {
            clearSnoozePreference(context, prefs);
        }
    }

    /**
     * Return an Alarm object representing the alarm id in the database.
     * Returns null if no alarm exists.
     */
    public static SpecialAlarm getAlarm(ContentResolver contentResolver, int alarmId) {
        Cursor cursor = contentResolver.query(
                ContentUris.withAppendedId(SpecialAlarm.Columns.CONTENT_URI, alarmId),
                SpecialAlarm.Columns.ALARM_QUERY_COLUMNS,
                null, null, null);
        SpecialAlarm alarm = null;
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                alarm = new SpecialAlarm(cursor);
            }
            cursor.close();
        }
        return alarm;
    }


    /**
     * A convenience method to set an alarm in the Alarms
     * content provider.
     * @return Time when the alarm will fire.
     */
    public static long setAlarm(Context context, SpecialAlarm alarm) {
    	int c1=count(context);
        ContentValues values = createContentValues(alarm);
        Log.v("=====+++++++____________==========");
        Log.v(String.valueOf(values.get(Columns.LOCATION)));
        ContentResolver resolver = context.getContentResolver();
        resolver.update(ContentUris.withAppendedId(SpecialAlarm.Columns.CONTENT_URI, alarm.id),
                values, null, null);

        int c2=count(context);
        long timeInMillis = calculateAlarm(alarm);

        if (alarm.enabled) {
        	//当用户小睡一个闹钟后，同时修改了一个闹钟，那就取消这个小睡的闹钟
        	//如果修改的闹钟和小睡的闹钟的时间是一样的
        	//才启用这个小睡闹钟
            disableSnoozeAlert(context, alarm.id);

            // Disable the snooze if this alarm fires before the snoozed alarm.
            //取消小睡如果说闹钟在小睡闹钟之前生效
            // This works on every alarm since the user most likely intends to
            // have the modified alarm fire next.
            clearSnoozeIfNeeded(context, timeInMillis);
        }
        updateStatusBarIcon(c1,c2,context);
        setNextAlert(context);

        return timeInMillis;
    }



    public static void enableAlarm(final Context context, final int id, boolean enabled){
        enableAlarmInternal(context, id, enabled);
        setNextAlert(context);
    }
    
    private static void enableAlarmInternal(final Context context,
            final int id, boolean enabled) {
        enableAlarmInternal(context, getAlarm(context.getContentResolver(), id),
                enabled);
    }

    
    /**
     * 激活一个闹钟时间小于当前时间的闹钟
     * 让这个闹钟在第二天的同一时间继续响应
     */
    private static void enableAlarmInternal(final Context context,
            final SpecialAlarm alarm, boolean enabled) {
        if (alarm == null) {
            return;
        }
        
        int c1=count(context);
        ContentResolver resolver = context.getContentResolver();

        ContentValues values = new ContentValues(2);
        values.put(SpecialAlarm.Columns.ENABLED, enabled ? 1 : 0);

  
        if (enabled) {
        	/**
        	 * 如果这个闹钟已经Enable，那就计算出它下次闹铃的时间
        	 * 并且把这个时间放入Value中
        	 */
            long time = 0;
         
                time = calculateAlarm(alarm);
       
            values.put(SpecialAlarm.Columns.ALARM_TIME, time);
        } else {
         /**
          * 如果这个闹钟没有Enable，则将这个闹钟的Snooze给清除掉
          */
            disableSnoozeAlert(context, alarm.id);
        }

        resolver.update(ContentUris.withAppendedId(SpecialAlarm.Columns.CONTENT_URI, alarm.id), values, null, null);
        int c2=count(context);
        updateStatusBarIcon(c1, c2, context);
    }

    public static Calendar getCalendar(int year,int month,int day,int hour,int minute)
    {
       Calendar c = Calendar.getInstance();
       c.setTimeInMillis(System.currentTimeMillis());
       int tempmonth = month +1;
       c.set(Calendar.YEAR, year);
       c.set(Calendar.MONTH,tempmonth);
       c.set(Calendar.DAY_OF_YEAR, day);
       c.set(Calendar.HOUR,hour);
       c.set(Calendar.MINUTE, minute);
       c.set(Calendar.SECOND, 0);
       c.set(Calendar.MILLISECOND, 0);
       return c;
    }
    
    
    //估算下一次闹钟
    public static SpecialAlarm calculateNextAlert(final Context context) {
       
    	SpecialAlarm specialalarm = null;
        long minTime = Long.MAX_VALUE;
        long now = System.currentTimeMillis();
        //返回当前数据库中所有已经激活的闹钟
        Cursor cursor = getFilteredAlarmsCursor(context.getContentResolver());
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    SpecialAlarm a = new SpecialAlarm(cursor);
                    
                    //a.time == 0；代表这个闹钟是一个可重复的闹钟
                    //所以计算这个闹钟下一次alert的时间
                    if (a.time == 0) {
                        a.time = calculateAlarm(a);
                    } else if (a.time < now) {
                        // 让这个闹钟失效
                        //enableAlarmInternal(context, a, false);
                        continue;
                    }
                    if (a.time < minTime) {
                        minTime = a.time;
                        specialalarm = a;
                    }
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return specialalarm;
    }

    /**
     * Disables non-repeating alarms that have passed.  Called at
     * boot.
     */
    public static void disableExpiredAlarms(final Context context) {
        Cursor cur = getFilteredAlarmsCursor(context.getContentResolver());
        long now = System.currentTimeMillis();
        boolean status=false;
        if (cur.moveToFirst()) {
            do {
                SpecialAlarm alarm = new SpecialAlarm(cur);
                // A time of 0 means this alarm repeats. If the time is
                // non-zero, check if the time is before now.
                if (alarm.time != 0 && alarm.time < now) {
                   
                        Log.v("** DISABLE " + alarm.id + " now " + now +" set "
                                + alarm.time);
                    
                    enableAlarmInternal(context, alarm, false);
                }else{
                	status=true;
                }
            } while (cur.moveToNext());
        }
        cur.close();
        if(status)
        	setStatusBarIcon(context, true);
    }

    /**
     *调用EnableAlaert.利用AlarmManager进行了闹钟设置
     */
    public static void setNextAlert(final Context context) {
    	
        if (!enableSnoozeAlert(context)) {
        	//如果Snooze没有被设置，就执行以下代码
        	//通过CalculateNextAlert，获得数据库中最近的一个Alarm
            SpecialAlarm alarm = calculateNextAlert(context);
            if (alarm != null) {
                enableAlert(context, alarm, alarm.time);
            } else {
                disableAlert(context);
            }
        }
    }
    

    /**
     * 调用了一个AlarmManager,用于设置时间
     *
     * @param alarm Alarm.
     * @param atTimeInMillis milliseconds since epoch
     */
    private static void enableAlert(Context context, final SpecialAlarm alarm,
            final long atTimeInMillis) {
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Log.v("** setAlert id " + alarm.id + " atTime " + atTimeInMillis);
        //利用Intent发送一个ALarm_ALERT_ACTION
        Intent intent = new Intent(SPECIALALARM_ALERT_ACTION);
        Parcel out = Parcel.obtain();
        alarm.writeToParcel(out, 0);
        out.setDataPosition(0);
        intent.putExtra(SPECIALALARM_RAW_DATA, out.marshall());
        //通过getBroadcast方法，将广播发送出去
        PendingIntent sender = PendingIntent.getBroadcast(
                context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        am.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, sender);

//        setStatusBarIcon(context, true);
        
        
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(atTimeInMillis);
        String timeString = formatDayAndTime(context, c);
        saveNextAlarm(context, timeString);
        Log.v("enableAlert\talarm.id:"+alarm.id);
    }

    /**
     * Disables alert in AlarmManger and StatusBar.
     *
     * @param id Alarm ID.
     */
    static void disableAlert(Context context) {
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, new Intent(SPECIALALARM_ALERT_ACTION),
                PendingIntent.FLAG_CANCEL_CURRENT);
        am.cancel(sender);
        setStatusBarIcon(context, false);
        saveNextAlarm(context, "");
    }
    
//    static void disableAlert(Context context,Alarm alarm) {
//        AlarmManager am = (AlarmManager)
//                context.getSystemService(Context.ALARM_SERVICE);
//        PendingIntent sender = PendingIntent.getBroadcast(
//                context, 0, new Intent(ALARM_ALERT_ACTION),
//                PendingIntent.FLAG_CANCEL_CURRENT);
//        am.cancel(sender);
//        setStatusBarIcon(context, false,alarm);
//        saveNextAlarm(context, "");
//        //����
//        Log.v("disableAlert\talarm.id:"+alarm.id);
//    }

    public static void saveSnoozeAlert(final Context context, final int id,
            final long time) {
        SharedPreferences prefs = context.getSharedPreferences(
                AlarmClock.PREFERENCES, 0);
        if (id == -1) {
            clearSnoozePreference(context, prefs);
        } else {
            SharedPreferences.Editor ed = prefs.edit();
            ed.putInt(PREF_SNOOZE_ID, id);
            ed.putLong(PREF_SNOOZE_TIME, time);
            ed.commit();
        }
        // Set the next alert after updating the snooze.
        setNextAlert(context);
    }

    /**
     * 当给定的ID等于某一个小睡闹钟的ID时，则取消该小睡Alert
     */
    static void disableSnoozeAlert(final Context context, final int id) {
        SharedPreferences prefs = context.getSharedPreferences(
                AlarmClock.PREFERENCES, 0);
        int snoozeId = prefs.getInt(PREF_SNOOZE_ID, -1);
        if (snoozeId == -1) {
            // 没有小睡设置.
            return;
        } else if (snoozeId == id) {
            // 因为给定的ID等于小睡闹钟的ID，所以执行清空小睡配置文件的操作
            clearSnoozePreference(context, prefs);
        }
    }

    // Helper to remove the snooze preference. Do not use clear because that
    // will erase the clock preferences. Also clear the snooze notification in
    // the window shade.
    private static void clearSnoozePreference(final Context context,final SharedPreferences prefs) {
    	
        final int alarmId = prefs.getInt(PREF_SNOOZE_ID, -1);
        if (alarmId != -1) {
            NotificationManager nm = (NotificationManager)
                    context.getSystemService(Context.NOTIFICATION_SERVICE);
            nm.cancel(alarmId);
        }

        final SharedPreferences.Editor ed = prefs.edit();
        ed.remove(PREF_SNOOZE_ID);
        ed.remove(PREF_SNOOZE_TIME);
        ed.commit();
    };

    /**
     * 如果存在一个Snooze设置，那就通过AlarmManger来进行Enable
     * @return true if snooze is set
     */
    private static boolean enableSnoozeAlert(final Context context) {
    	//通过Context参数，获得SharePrefrences
        SharedPreferences prefs = context.getSharedPreferences(AlarmClock.PREFERENCES, 0);

        int id = prefs.getInt(PREF_SNOOZE_ID, -1);
        
        if (id == -1) {
            return false;
        }
        long time = prefs.getLong(PREF_SNOOZE_TIME, -1);

        // Get the alarm from the db.
        final SpecialAlarm alarm = getAlarm(context.getContentResolver(), id);
        if (alarm == null) {
            return false;
        }
        // The time in the database is either 0 (repeating) or a specific time
        // for a non-repeating alarm. Update this value so the AlarmReceiver
        // has the right time to compare.
        alarm.time = time;

        enableAlert(context, alarm, time);
        return true;
    }

    /**
     * Tells the StatusBar whether the alarm is enabled or disabled
     */
//    private static void setStatusBarIcon(Context context, boolean enabled) {
//        Intent alarmChanged = new Intent("android.intent.action.ALARM_CHANGED");
//        alarmChanged.putExtra("alarmSet", enabled);
//        context.sendBroadcast(alarmChanged);
//    }
    
    private static void setStatusBarIcon(Context context, boolean enabled) {
    	Log.v("setStatusBarIcon\t"+"setStatusBarIcon");
    	Notification n = new Notification();
    	Intent viewAlarm = new Intent(context, AlarmClock.class);
    	PendingIntent intent = PendingIntent.getActivity(context,0, viewAlarm, 0);
    	n.icon=R.drawable.ic_clock_alarm_selected;
		n.setLatestEventInfo(context, "",context.getString(R.string.alarm_notify_text),intent);
		n.flags |= Notification.FLAG_SHOW_LIGHTS| Notification.FLAG_ONGOING_EVENT;
		n.defaults |= Notification.DEFAULT_LIGHTS;

		// Send the notification using the alarm id to easily identify the
		// correct notification.
		NotificationManager nm =(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		Log.v("enabled\t"+enabled);
		if(enabled)
			nm.notify(1216, n);
		else
			nm.cancel(1216);
  }
//计算到下一个闹钟还有多久
    private static long calculateAlarm(SpecialAlarm alarm) {
        return
       calculateAlarm(alarm.year,alarm.month,alarm.day,alarm.hour, alarm.minutes).getTimeInMillis();
    }

    /**
     * Given an alarm in hours and minutes, return a time suitable for
     * setting in AlarmManager.
     */
    static Calendar calculateAlarm(int year,int month,int day ,int hour, int minute) {

        // start with now
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());

        int nowHour = c.get(Calendar.HOUR_OF_DAY);
        int nowMinute = c.get(Calendar.MINUTE);
        
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month);
        c.set(Calendar.DAY_OF_MONTH, day);
        // if alarm is behind current time, advance one day
        if (hour < nowHour  ||
            hour == nowHour && minute <= nowMinute) {
            c.add(Calendar.DAY_OF_MONTH, 1);
        }
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c;
    }

    static Calendar calculateAlarm(int hour, int minute) {

        // start with now
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());

        int nowHour = c.get(Calendar.HOUR_OF_DAY);
        int nowMinute = c.get(Calendar.MINUTE);
        // if alarm is behind current time, advance one day
        if (hour < nowHour  ||
            hour == nowHour && minute <= nowMinute) {
            c.add(Calendar.DAY_OF_MONTH, 1);
        }
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c;
    }
    //规范显示Time
    static String formatTime(final Context context, int hour, int minute) {
        Calendar c = calculateAlarm(hour, minute);
        return formatTime(context, c);
    }
   //规范显示Date
    public static String formatDate(final Context context,int year,int month,int day)
    {
    	int temp = month+1;
    	String str = year+"年"+temp+"月"+day+"日";
        return str;
    }
    
    public String formatDate(int year,int month,int day)
    {
    	int temp = month+1;
    	String str = year+"年"+temp+"月"+day+"日";
        return str;
    }
    
    
    /* used by AlarmAlert */
    public static String formatTime(final Context context, Calendar c) {
        String format = get24HourMode(context) ? M24 : M12;
        return (c == null) ? "" : (String)DateFormat.format(format, c);
    }

    /**
     * Shows day and time -- used for lock screen
     */
    private static String formatDayAndTime(final Context context, Calendar c) {
        String format = get24HourMode(context) ? DM24 : DM12;
        return (c == null) ? "" : (String)DateFormat.format(format, c);
    }

    /**
     * Save time of the next alarm, as a formatted string, into the system
     * settings so those who care can make use of it.
     */
    static void saveNextAlarm(final Context context, String timeString) {
        Settings.System.putString(context.getContentResolver(),
                                  Settings.System.NEXT_ALARM_FORMATTED,
                                  timeString);
    }

    /**
     * @return true if clock is set to 24-hour mode
     */
    static boolean get24HourMode(final Context context) {
        return android.text.format.DateFormat.is24HourFormat(context);
    }
}
